/* GStreamer
 * Copyright (C) <2008> Andre Moreira Magalhaes <andrunko@gmail.com>
 * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
 * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gst/gst.h>

#include <stdlib.h>

#define UPDATE_INTERVAL    500
#define CROSSFADE_DURATION 5000

static GMainLoop *loop;
static GstElement *pipeline, *crossfade, *sink;
static const gchar *next_uri;

static void
cb_newpad (GstElement * element, GstPad * pad, gboolean last, gpointer data)
{
  GstCaps *caps;
  GstStructure *str;
  GstPad *sinkpad;
  GstElement *audioconvert = NULL;
  const gchar *name;
  GstStateChangeReturn ret;
  GstPadLinkReturn lret;

  /* check media type */
  caps = gst_pad_get_caps (pad);
  str = gst_caps_get_structure (caps, 0);

  name = gst_structure_get_name (str);
  g_print ("new pad found name: %s\n", name);

  if (g_strrstr (name, "audio")) {
    audioconvert = gst_element_factory_make ("audioconvert", NULL);
  }
  gst_caps_unref (caps);

  if (audioconvert) {
    GstElement *queue;

    queue = gst_element_factory_make ("queue", NULL);

    /* add new audio convert to the pipeline */
    gst_bin_add_many (GST_BIN_CAST (pipeline), queue, audioconvert, NULL);

    /* set the new audioconvert to PAUSED as well */
    ret = gst_element_set_state (queue, GST_STATE_PAUSED);
    ret = gst_element_set_state (audioconvert, GST_STATE_PAUSED);
    if (ret == GST_STATE_CHANGE_FAILURE)
      goto state_error;

    gst_element_link_many (queue, audioconvert, crossfade, NULL);

    /* get the ghostpad of the audioconvert */
    sinkpad = gst_element_get_pad (queue, "sink");

    /* link'n'play */
    lret = gst_pad_link (pad, sinkpad);
    if (lret != GST_PAD_LINK_OK)
      goto link_failed;

    gst_object_unref (sinkpad);
  }
  return;

  /* ERRORS */
state_error:
  {
    gst_bin_remove (GST_BIN_CAST (pipeline), audioconvert);
    g_warning ("could not change state of new audioconvert (%d)", ret);
    return;
  }
link_failed:
  {
    g_warning ("could not link pad and audioconvert (%d)", lret);
    return;
  }
}

static gboolean
update_scale (GstElement * element)
{
  gint64 duration = -1;
  gint64 position = -1;
  GstFormat format = GST_FORMAT_TIME;
  gchar dur_str[32], pos_str[32];

  if (gst_element_query_position (element, &format, &position) &&
      position != -1) {
    g_snprintf (pos_str, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (position));
  } else {
    g_snprintf (pos_str, 32, "-:--:--.---------");
  }

  if (gst_element_query_duration (element, &format, &duration) &&
      duration != -1) {
    g_snprintf (dur_str, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (duration));
  } else {
    g_snprintf (dur_str, 32, "-:--:--.---------");
  }

  g_print ("%s / %s\n", pos_str, dur_str);

  if (next_uri &&
      GST_TIME_AS_MSECONDS (duration) - GST_TIME_AS_MSECONDS (position) < CROSSFADE_DURATION) {
    GstElement *filesrc, *decodebin;

    // gst_element_set_state (pipeline, GST_STATE_PAUSED);

    g_print ("crosfading to %s...\n", next_uri);

    filesrc = gst_element_factory_make ("filesrc", NULL);
    g_assert (filesrc);
    decodebin = gst_element_factory_make ("decodebin2", NULL);
    g_assert (decodebin);

    g_signal_connect (G_OBJECT (decodebin), "new-decoded-pad",
        G_CALLBACK (cb_newpad), NULL);

    gst_bin_add_many (GST_BIN (pipeline), filesrc, decodebin, NULL);

    gst_element_link (filesrc, decodebin);

    g_object_set (G_OBJECT (filesrc), "location", next_uri, NULL);

    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    next_uri = NULL;
  }

  return TRUE;
}

gint
main (gint argc, gchar * argv[])
{
  GstElement *filesrc, *decodebin;
  GstStateChangeReturn res;

  gst_init (&argc, &argv);

  if (argc != 3) {
    g_print ("usage: %s <uri1> <uri2>\n", argv[0]);
    exit (-1);
  }

  next_uri = argv[2];

  pipeline = gst_pipeline_new ("pipeline");

  filesrc = gst_element_factory_make ("filesrc", "filesrc");
  g_assert (filesrc);
  decodebin = gst_element_factory_make ("decodebin2", "decodebin");
  g_assert (decodebin);

  g_signal_connect (G_OBJECT (decodebin), "new-decoded-pad",
      G_CALLBACK (cb_newpad), NULL);

  gst_bin_add_many (GST_BIN (pipeline), filesrc, decodebin, NULL);
  gst_element_link (filesrc, decodebin);

  crossfade = gst_element_factory_make ("crossfade", "crossfade");
  g_assert (crossfade);
  g_object_set (G_OBJECT (crossfade), "duration", CROSSFADE_DURATION, NULL);
  sink = gst_element_factory_make ("gconfaudiosink", "sink");
  g_assert (sink);

  gst_bin_add_many (GST_BIN (pipeline), crossfade, sink, NULL);
  gst_element_link (crossfade, sink);

  g_object_set (G_OBJECT (filesrc), "location", argv[1], NULL);

  /* set to paused, decodebin will autoplug and signal new_pad callbacks */
  res = gst_element_set_state (pipeline, GST_STATE_PAUSED);
  if (res == GST_STATE_CHANGE_FAILURE) {
    g_print ("could not pause\n");
    return -1;
  }
  /* wait for paused to complete */
  res = gst_element_get_state (pipeline, NULL, NULL, GST_CLOCK_TIME_NONE);
  if (res == GST_STATE_CHANGE_FAILURE) {
    g_print ("could not pause\n");
    return -1;
  }

  /* play, now all the sinks are added to the pipeline and are prerolled and
   * ready to play. */
  res = gst_element_set_state (pipeline, GST_STATE_PLAYING);
  if (res == GST_STATE_CHANGE_FAILURE) {
    g_print ("could not play\n");
    return -1;
  }

  g_print ("playing ...\n");

  g_timeout_add (UPDATE_INTERVAL, (GSourceFunc) update_scale, pipeline);

  /* go in the mainloop now */
  loop = g_main_loop_new (NULL, TRUE);
  g_main_loop_run (loop);

  return 0;
}
